<template>
  <div class="tabs-container">
    <div class="tabs-wrapper">
      <div
        v-for="tab in visitedTabs"
        :key="tab.path"
        :class="['tab-item', { 'is-active': isActive(tab) }]"
        @click="handleClick(tab)"
      >
        <span class="tab-title">{{ tab.title }}</span>
        <span class="tab-close" @click.stop="handleClose(tab)">×</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    visitedTabs () {
      return this.$store.state.tagsView.visitedViews
    },
    currentRoute () {
      return this.$route
    }
  },

  methods: {
    isActive (tab) {
      return tab.path === this.currentRoute.path
    },

    handleClick (tab) {
      if (this.currentRoute.path !== tab.path) {
        this.$router.push(tab.path)
      }
    },

    handleClose (tab) {
      this.$store.dispatch('tagsView/closeView', tab).then(lastView => {
        if (this.isActive(tab)) {
          this.$router.push(lastView.path)
        }
      })
    }
  }
}
</script>

<style scoped>
.tabs-container {
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  height: 34px;
}

.tabs-wrapper {
  display: flex;
  padding: 0 15px;
  overflow-x: auto;
}

.tab-item {
  height: 26px;
  line-height: 26px;
  border: 1px solid #d8dce5;
  color: #495060;
  background: #fff;
  padding: 0 8px;
  font-size: 12px;
  margin: 4px 5px 0 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  border-radius: 3px;
}

.tab-item.is-active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

.tab-title {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tab-close {
  margin-left: 5px;
  font-size: 14px;
  transition: all 0.3s;
}

.tab-close:hover {
  color: #f56c6c;
  transform: scale(1.2);
}
</style>
